package controller;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Callable;

import model.ContactModel;
import model.ContactsModel;

public class LoaderCallable implements Callable<ArrayList<ContactModel>> {

	private static BufferedReader br = null;

	static {
		try {
			br = new BufferedReader(new FileReader(ContactsModel.FILE_NAME));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public static void closeBufferReader(){
		try {
			br.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	

	@Override
	public ArrayList<ContactModel> call() throws Exception {
		String line = "";
		ArrayList<ContactModel> list = new ArrayList<ContactModel>();
		while ((line = br.readLine()) != null) {
			String[] contactItems = line.split(ContactsModel.cvsSplitBy);
			ContactModel contactModel = new ContactModel();
			if (contactItems.length == contactModel.parametersCount) {
				contactModel.setFirstName(contactItems[0].trim());
				contactModel.setLastName(contactItems[1].trim());
				contactModel.setHomeAddress(contactItems[2].trim());
				contactModel.setCompanyAddress(contactItems[3].trim());
				contactModel.setPersonMobilePhone(contactItems[4].trim());
				contactModel.setPersonHomePhone(contactItems[5].trim());
				contactModel.setProfessionalMobilePhone(contactItems[6].trim());
				contactModel.setProfessionalOfficePhone(contactItems[7].trim());
				contactModel.setHomePage(contactItems[8].trim());
				contactModel.setProfessionalEmail(contactItems[9].trim());
				contactModel.setPersonalEmail(contactItems[10].trim());
				contactModel.setOther(contactItems[11].trim());
				contactModel.setImagePath(contactItems[12].trim());
				contactModel.setGroup(contactItems[13].trim());
				contactModel.setId(Integer.parseInt(contactItems[14].trim()));
				list.add(contactModel);
			} else {
				return null;
			}
		}
		return list;
	}

}
